package com.example.android.utils.livedata;

import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.concurrent.atomic.AtomicBoolean


class MyLiveData<T>(call: Call<T>) : LiveData<T>() {
    private val started: AtomicBoolean = AtomicBoolean(false)
    private val call: Call<T>

    // 在 observer 由 0变1 时会调用
    override fun onActive() {
        super.onActive()
        if (started.compareAndSet(false, true)) {
            call.enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    super@MyLiveData.postValue(response.body())
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    super@MyLiveData.postValue(null)
                }
            })
        }
    }

    init {
        this.call = call
    }
}